﻿/****************************************************************************
Copyright (c) 2014-2015 凌惊雪 微信:Lingjingxue 邮箱:lingjingxue@sina.com QQ:271487457

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

using UtilPublic.Mysql;
using UtilPublic.ServerLoger;
using System;
using System.Diagnostics;
using System.Threading;
using UtilLib;
using ServerBase.Config;
using System.Collections.Concurrent;
using UtilPublic.Const;
using ServerBase.LunarSocket;
using System.Collections.Generic;
using System.Threading.Tasks;
using ServerBase.Service;
using UtilPublic;
using WebSocketSharp.Server;
using WebSocketSharp;
using ServerBase.Protocol;

namespace ServerBase.LunarSocket
{
    public class LunarSession : WebSocketBehavior
    {
        public string Sid => base.ID;
        //是否链接
        public bool IsConnected => this.ConnectionState == WebSocketState.Open;
        public string IpAddress()
        {
            //return this.RemoteEndPoint.AddressFamily.ToString();
            return "未知IP";
        }

        // 唯一ID(当类型为客户端时为用户唯一ID 当类型为其他服务器时为服务器ID)
        public long SessionUuid;

        // 玩家唯一ID
        public long Puid;

        // 平台序号
        public string Account = "";

        // 连接类型(表明连接来自客户端开始其他服务器 默认为0=客户端)
        public short SessionType { get; set; } = 0;

        // 连接状态
        public bool Loginded = false;


        // 绑定对象
        public ILunarSession SessionObj = null;

        //接收消息队列
        public ConcurrentQueue<LunarRequestInfo> ListReq = new ConcurrentQueue<LunarRequestInfo>();

        protected override void OnOpen()
        {
            loger.Debug("接收到连接: " + Sid);

            Send(new G2C_Login_Connect());
        }
        protected override void OnClose(CloseEventArgs e)
        {
            loger.Debug("断开连接: " + Sid);
        }
        protected override void OnMessage(MessageEventArgs e)
        {
            try
            {
                if (!BaseAppServer.AllSessions.ContainsKey(Sid))
                {
                    BaseAppServer.AllSessions.TryAdd(Sid, this);
                }
                var msg = new LunarRequestInfo(e.Data);
                ListReq.Enqueue(msg);
            }
            catch (Exception ex)
            {
                loger.Warn($"{e.Data}");
                loger.Error($"OnMessage", ex);
                Send(new G2C_Base_Result() { Shuttle = $"{Sid} 错误的消息" });
            }
        }
        protected override void OnError(ErrorEventArgs e)
        {
            loger.Error(e.Message, e.Exception);
        }
        //打包发送消息
        public void Send<T>(T msg) where T : ProtocolMsgBase
        {
            var nbs = LunarRequestInfo.From(msg);
            if (loger.GetLevel() <= ELogLevel.Info)
            {
                var id = nbs.ProtocolID;
                var result = nbs.Result;
                loger.Info($"发送数据包 Puid：{Puid} 协议号：{id}->{(int)id} 错误码：{result}->{(int)result} 长度：{nbs.Length}");
            }
            if (loger.临时调试开关)
            {
                loger.DDD(nbs.Body);
            }
            Send(nbs);
        }
        public void Send(LunarRequestInfo message)
        {
            if (!IsConnected)
            {
                return;
            }
            base.Send(message.Body);
        }
        public void TryClose()
        {
            base.Close();
        }

    }
}
